package com.kexuexiong.demo.bear.job;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRuleManager;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.slots.system.SystemRule;
import com.alibaba.csp.sentinel.slots.system.SystemRuleManager;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Objects;

/**
 * sentinel 定时器
 */
@Component
@Slf4j
public class SentinelJobHandle {

    String flowRuleMD5 = "";

    String systemRuleMD5 = "";

    String degradeRuleMD5 = "";

    /**
     * 同步flow配置
     *
     * @throws FileNotFoundException
     */
    @XxlJob("sentinelFlowConfigListenerJobHandler")
    public void sentinelConfigListenerJobHandler() throws FileNotFoundException {
        File backFile = null;
        try {
            List<FlowRule> rules = FlowRuleManager.getRules();
            String jsonStr = JSONUtil.toJsonStr(rules);
            String md5Hex = MD5Utils.md5Hex(jsonStr, "UTF-8");
            if (Objects.equals(md5Hex, flowRuleMD5)) {
                return;
            }
            flowRuleMD5 = md5Hex;
            File file = new File("config/sentinel/back/FlowRule.json");
            backFile = new File("config/sentinel/back/FlowRule-back.json");
            FileUtil.appendString(jsonStr, backFile, "UTF-8");
            file.deleteOnExit();
            file.createNewFile();
            FileUtil.copy(backFile, file, true);
        } catch (Exception e) {
            log.error("sentinelFlowConfigListenerJobHandler 出错：{}", e.getMessage());
        } finally {
            if (Objects.nonNull(backFile) && backFile.exists()) {
                backFile.delete();
            }
        }

    }

    /**
     * 同步degrade配置
     *
     * @throws FileNotFoundException
     */
    @XxlJob("sentinelDegradeConfigListenerJobHandler")
    public void sentinelDegradeConfigListenerJobHandler() throws FileNotFoundException {
        File backFile = null;
        try {
            List<DegradeRule> rules = DegradeRuleManager.getRules();
            String jsonStr = JSONUtil.toJsonStr(rules);
            String md5Hex = MD5Utils.md5Hex(jsonStr, "UTF-8");
            if (Objects.equals(md5Hex, degradeRuleMD5)) {
                return;
            }
            flowRuleMD5 = md5Hex;
            File file = new File("config/sentinel/back/DegradeRule.json");
            backFile = new File("config/sentinel/back/DegradeRule-back.json");
            FileUtil.appendString(jsonStr, backFile, "UTF-8");
            file.deleteOnExit();
            file.createNewFile();
            FileUtil.copy(backFile, file, true);
        } catch (Exception e) {
            log.error("sentinelDegradeConfigListenerJobHandler 出错：{}", e.getMessage());
        } finally {
            if (Objects.nonNull(backFile) && backFile.exists()) {
                backFile.delete();
            }
        }
    }

    /**
     * 同步system配置
     *
     * @throws FileNotFoundException
     */
    @XxlJob("sentinelSystemConfigListenerJobHandler")
    public void sentinelSystemConfigListenerJobHandler() throws FileNotFoundException {
        File backFile = null;
        try {
            List<SystemRule> rules = SystemRuleManager.getRules();
            String jsonStr = JSONUtil.toJsonStr(rules);
            String md5Hex = MD5Utils.md5Hex(jsonStr, "UTF-8");
            if (Objects.equals(md5Hex, systemRuleMD5)) {
                return;
            }
            flowRuleMD5 = md5Hex;
            File file = new File("config/sentinel/back/SystemRule.json");
            backFile = new File("config/sentinel/back/SystemRule-back.json");
            FileUtil.appendString(jsonStr, backFile, "UTF-8");
            file.deleteOnExit();
            file.createNewFile();
            FileUtil.copy(backFile, file, true);
        } catch (Exception e) {
            log.error("sentinelSystemConfigListenerJobHandler 出错：{}", e.getMessage());
        } finally {
            if (Objects.nonNull(backFile) && backFile.exists()) {
                backFile.delete();
            }
        }
    }
}
